package com.ilongsay.service.impl;

import com.ilongsay.dao.BillDao;
import com.ilongsay.entity.FaPiao;
import com.ilongsay.entity.FaPiaoDetail;
import com.ilongsay.entity.Input;
import com.ilongsay.service.IBillService;
import com.ilongsay.zhujie.DataSource;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * @Author ilongsay
 * @Email ilongsay@163.com
 * @Copyright 版本所有，侵权必究！
 * @Datetime 2018-11-11 5:02
 * @Describution
 */

@Service("billService")
public class BillServiceImpl implements IBillService{

    @Autowired
    private BillDao billDao;

    /**
     * @param
     * @return java.util.List<com.ilongsay.entity.FaPiao>
     * 导入全部数据，不设置参数，已经废弃不建议使用
     */
    @Override
    @Deprecated
    public List<FaPiao> findAllBill() {
        return billDao.findBill();
    }

    /**
     * @param input 用户的导入设置参数
     * @return java.util.List<com.ilongsay.entity.FaPiao>
     * 根据导入的参数获取数据
     */
    @Override
    public List<FaPiao> findByParams(Input input) {

        List<FaPiao> faPiaos = billDao.findBillByParams(input);
        for (FaPiao faPiao : faPiaos) {//遍历订单号
            StringBuilder note;
            Set<String> billNote = new TreeSet<>();
            for (FaPiaoDetail faPiaoDetail : faPiao.getFaPiaoDetails()) {
                note = new StringBuilder();

                if (faPiaoDetail.getNotes() != null && faPiao.getNote() != null) {
                    //如果明细的备注不为null，主表备注不为null，拼接明细备注和主表备注
                    note.append(faPiaoDetail.getNotes()).append(",").append(faPiao.getNote());//将主表备注与明细备注拼接
                    faPiaoDetail.setNotes(note.toString());//设置明细订单信息
                }else if (faPiaoDetail.getNotes() == null && faPiao.getNote() != null ){
                    //如果明细的备注为null，，主表备注不为null仅仅只拼接主表的备注
                    note.append(faPiao.getNote());
                    faPiaoDetail.setNotes(note.toString());//设置明细订单信息
                }else if (faPiaoDetail.getNotes() == null && faPiao.getNote() == null) {
                    faPiaoDetail.setNotes(null);
                }

                billNote.add(faPiaoDetail.getNotes());//将每一条明细的备注信息存入到set中，达到去重效果
            }
            String[] notes = billNote.toString().
                                replace("[","").
                                replace("]","").replace(" ","").
                                split(",");
            Set<String> noteSet = new TreeSet<>();
            for (String note1 : notes) {
                noteSet.add(note1);
            }
            faPiao.setNote(noteSet.toString().replace("[","").replace("]",""));
        }
        return faPiaos;
    }

}
